package com.bowlong.third.redis.lang;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import redis.clients.jedis.Jedis;

public class JedisMap {
	final Jedis jedis;
	final String pkey;

	public JedisMap(Jedis jedis, String pkey) {
		this.jedis = jedis;
		this.pkey = pkey;
	}

	public int size() {
		return this.jedis.hlen(pkey).intValue();
	}

	public boolean isEmpty() {
		return size() <= 0;
	}

	public boolean containsKey(String key) {
		return this.jedis.hexists(pkey, key);
	}

	public String get(String key) {
		return this.jedis.hget(pkey, key);
	}

	public List<String> getAll(String... keys) {
		List<String> r = new Vector<>();
		List<String> vals = this.jedis.mget(keys);
		for (String text : vals) {
			r.add(text);
		}
		return r;
	}

	public String put(String key, String text) {
		this.jedis.hset(pkey, key, text);
		return text;
	}

	public String remove(String key) {
		String text = this.jedis.hget(pkey, key);
		this.jedis.hdel(pkey, key);
		return text;
	}

	public void putAll(Map<? extends String, ? extends String> m) {
		Map<String, String> hash = new HashMap<>();
		Set<? extends String> keys = m.keySet();
		for (String key : keys) {
			String value = m.get(key);
			hash.put(key, value);
		}
		this.jedis.hmset(pkey, hash);
	}

	public void clear() {
		this.jedis.del(pkey);
	}

	public Set<String> keySet() {
		Set<String> r2 = new HashSet<>();
		Set<String> keys = this.jedis.hkeys(pkey);
		for (String text : keys) {
			r2.add(text);
		}
		return r2;
	}

	public Collection<String> values() {
		List<String> r2 = new Vector<>();
		List<String> values = this.jedis.hvals(pkey);
		for (String text : values) {
			r2.add(text);
		}
		return r2;
	}

	public Set<java.util.Map.Entry<String, String>> entrySet() {
		Map<String, String> map = new HashMap<>();
		Map<String, String> datas = this.jedis.hgetAll(pkey);
		Set<Entry<String, String>> ens = datas.entrySet();
		for (Entry<String, String> entry : ens) {
			String key = entry.getKey();
			String text = entry.getValue();
			map.put(key, text);
		}
		return map.entrySet();
	}

}
